package org.example.erat.strategy;

import org.example.erat.dto.ExperimentStatisticsDTO;
import org.example.erat.entity.ClassEntity;
import org.example.erat.entity.Course;
import org.example.erat.entity.Experiment;
import org.example.erat.entity.Student;
import org.example.erat.log.core.LoggerSingleton;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 实验维度统计策略
 * 按实验维度统计提交情况
 */
@Component
public class ExperimentStatisticsStrategy implements StatisticsStrategy {

    @Override
    public Map<String, Object> execute(ClassEntity classEntity, Course course,
                                     List<Student> students, List<Experiment> experiments,
                                     Map<String, Object> reportData) {
        LoggerSingleton.getInstance().info("执行实验维度统计策略");

        Map<String, Object> result = new HashMap<>();
        List<ExperimentStatisticsDTO> experimentStatistics = new ArrayList<>();

        // 获取已提交的学生ID集合
        @SuppressWarnings("unchecked")
        Map<String, Set<String>> submittedStudentIds = (Map<String, Set<String>>) reportData.getOrDefault("submittedStudentIds", new HashMap<>());

        // 计算每个实验的统计数据
        for (Experiment experiment : experiments) {
            ExperimentStatisticsDTO stats = new ExperimentStatisticsDTO();
            stats.setExperimentName(experiment.getName());
            stats.setTotalStudents(students.size());

            // 获取已提交该实验的学生ID集合
            Set<String> submittedIds = submittedStudentIds.getOrDefault(experiment.getName(), new HashSet<>());
            stats.setSubmittedCount(submittedIds.size());
            stats.setMissingCount(students.size() - submittedIds.size());

            // 计算提交率
            if (stats.getTotalStudents() > 0) {
                stats.setSubmissionRate((double) stats.getSubmittedCount() / stats.getTotalStudents());
            } else {
                stats.setSubmissionRate(0.0);
            }

            // 获取缺交学生列表
            List<Map<String, Object>> missingStudents = new ArrayList<>();
            for (Student student : students) {
                if (!submittedIds.contains(student.getStudentId())) {
                    Map<String, Object> missingStudent = new HashMap<>();
                    missingStudent.put("id", student.getId());
                    missingStudent.put("studentId", student.getStudentId());
                    missingStudent.put("name", student.getName());
                    missingStudents.add(missingStudent);
                }
            }
            stats.setMissingStudents(missingStudents);

            experimentStatistics.add(stats);
        }

        result.put("experimentStatistics", experimentStatistics);

        LoggerSingleton.getInstance().info("实验维度统计完成，共 {} 个实验", experimentStatistics.size());
        return result;
    }

    @Override
    public String getName() {
        return "experiment";
    }
}
